package com.googlecode.ddlutilstool.logging;

import java.util.ArrayList;

import org.apache.log4j.WriterAppender;
import org.apache.log4j.spi.ErrorCode;
import org.apache.log4j.spi.LoggingEvent;

/**
 * <p>A Log4j appender that can be used to output to various
 * destinations.  Any class that logs in as an Observer of this
 * appender will get a callback each each log event.</p>
 * 
 * <p>In the DDLTool, this is used to map the Log4j output
 * to a swing edit box while performing DDL actions.</p>
 * 
 * <p>This appender is configured from within the log4j properties.</p>
 * @author critchie
 *
 */
public class Log4JWriterObserable extends WriterAppender {

	static ArrayList<Log4jWriterObserver> mObservers = new ArrayList<Log4jWriterObserver>();
	
	/**
	 * <p>Adds an observer.  Any object passed into this method
	 * will receive all Log4j messages from that point on.</p>
	 * 
	 * @param pObserver the class to be called back to with log4j messages
	 */
	public static void addObserver(Log4jWriterObserver pObserver) {
		mObservers.add(pObserver);
	}
	
	/**
	 * <p>Called by Log4j with each new message event.
	 * This method will pass on the event content to
	 * each observer.</p> 
	 * 
	 * @see org.apache.log4j.WriterAppender#append(org.apache.log4j.spi.LoggingEvent)
	 */
	public void append(LoggingEvent event) {
		if (mObservers.size()==0) {
			return;
		}
		
		if( this.layout == null) {
			errorHandler.error("No layout for appender " + name ,null, ErrorCode.MISSING_LAYOUT );
			return;
		}
		
		String message = this.layout.format(event);
		
		for (Log4jWriterObserver observer : mObservers) {
			observer.append(message);
		}
	}

	

}
